package com.yu.waterstation.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.yu.waterstation.app.moudles.student.service.StudentService;
import com.yu.waterstation.app.moudles.worker.service.WorkerService;
import com.yu.waterstation.common.annotation.GuestAccess;
import com.yu.waterstation.common.annotation.NeedToken;
import com.yu.waterstation.common.constant.Const;
import com.yu.waterstation.common.enums.TokenType;
import com.yu.waterstation.common.exception.handler.ServiceException;
import com.yu.waterstation.common.util.jwt.JWTUtil;
import com.yu.waterstation.common.util.servlet.ServletUtils;
import com.yu.waterstation.common.util.session.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Objects;

/**
 * api拦截器
 */
@Slf4j
@Component
public class AppApiInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ((handler instanceof HandlerMethod)) {
            NeedToken annotation = ((HandlerMethod) handler).getMethod().getAnnotation(NeedToken.class);
            if (annotation == null)
                return super.preHandle(request, response, handler);

            String token = SessionUtil.getToken(request);
            if (StringUtils.isEmpty(token) || !JWTUtil.verify(token)) {
                response.setHeader("Content-Type", "application/json;charset=UTF-8 ");
                response.getWriter().println("{\"code\":10001,\"message\":\"token无效\",\"data\":null}");
                response.flushBuffer();
                return false;
            }

            // 检验登录
            Integer userId = JWTUtil.getUserId(token);
            if (annotation.value() == TokenType.ENUM_student_token) {
                // 检验登录
                if (userId == null || !SessionUtil.checkStudentLogin(userId)) {
                    renderResponse(request, response);
                    return false;
                }
                request.setAttribute(Const.COSNT_student_id, userId);
            }
            if (annotation.value() == TokenType.ENUM_worker_token) {
                // 检验登录
                if (userId == null || !SessionUtil.checkWorkerLogin(userId)) {
                    renderResponse(request, response);
                    return false;
                }
                request.setAttribute(Const.COSNT_worker_id, userId);
            }

            // 游客模式
            if (userId == 0 && ((HandlerMethod) handler).getMethod().getAnnotation(GuestAccess.class) == null) {
                response.setHeader("Content-Type", "application/json;charset=UTF-8 ");
                response.getWriter().println("{\"code\":10003,\"message\":\"游客模式，禁止修改\",\"data\":null}");
                response.flushBuffer();
                return false;
            }
        }
        return super.preHandle(request, response, handler);
    }



    private void renderResponse(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Content-Type", "application/json;charset=UTF-8 ");
        response.getWriter().println("{\"code\":10001,\"message\":\"未登录或登录已过期\",\"data\":null}");
        response.flushBuffer();
    }

}
